import threading
from pathlib import Path
from typing import Optional, Union
from loguru import logger
from .log import Log
import subprocess as sp


class Logcat(Log):
    def __init__(self, save_path: Union[str, Path, None] = None, buffer_size: int = 1024):
        super().__init__(save_path, buffer_size)
        self._process: Optional[sp.Popen] = None

    def read(self):
        logger.info('start read')
        if self._process is None:
            logger.info('self._process is None')
            return
        while True:
            while True:
                process_status = True if self._process.poll() is None else False  # 进程状态
                if not process_status:
                    logger.info('进程状态异常')
                    self._process = sp.Popen('adb logcat', stdout=sp.PIPE, shell=True)
                    continue
                break

            if self.kill_catch_thread:
                logger.info(f'process_status:{process_status},'
                            f'kill_catch_thread:{self.kill_catch_thread}')
                break
            # 将日志写入队列
            line = self._process.stdout.readline()
            self.log_deque.append(line)
            logger.info(line)
            with open(self.save_path, 'a',errors='ignore') as f:
                f.write(line.decode(errors='ignore'))

    def start_catch(self):
        logger.info('开始获取logcat')
        super().start_catch()
        self._process = sp.Popen('adb logcat', stdout=sp.PIPE, shell=True)
        t = threading.Thread(target=self.read)
        t.daemon = True
        t.start()


if __name__ == '__main__':
    logger.add('run.log')
    logcat = Logcat()
    logcat.start_catch()
    input()
    logcat.stop_catch()
